package org.jeecg.modules.controller;

import cn.hutool.extra.pinyin.PinyinUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.modules.inquiry.entity.InquiryInfo;
import org.jeecg.common.modules.inquiry.service.IInquiryInfoService;
import org.jeecg.common.modules.patient.entity.Patient;
import org.jeecg.common.modules.patient.service.IPatientService;
import org.jeecg.common.modules.sms.entity.Captchar;
import org.jeecg.common.modules.sms.service.ICaptcharService;
import org.jeecg.common.modules.wx.entity.WxUserinfo;
import org.jeecg.common.modules.wx.service.IWxUserinfoService;
import org.jeecg.common.util.DySmsEnum;
import org.jeecg.common.util.DySmsHelper;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.ValidateUtils;
import org.jeecg.common.util.result.Result;
import org.jeecg.common.util.result.ResultMapper;
import org.jeecg.modules.data.Common;
import org.jeecg.modules.service.ApiInquiryService;
import org.jeecg.modules.vo.request.InquiryRequestVo;
import org.jeecg.modules.vo.request.PatientRequestVo;
import org.jeecg.modules.vo.respone.InquiryResponseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Objects;
@Slf4j
@RestController
@RequestMapping("api/v1/patient")
public class PatientController extends BaseController {
    @Resource
    private IWxUserinfoService wxUserinfoService;
    @Resource
    private IPatientService patientService;
    @Resource
    private IInquiryInfoService inquiryInfoService;
    @Resource
    private ApiInquiryService apiInquiryService;

    @Resource
    private ICaptcharService captcharService;
    @Resource
    private RedisUtil redisUtil;

    @GetMapping("/list")
    public Result getPatientListByOpenId(HttpServletRequest req) {
        String openId = null;
        try{
            if(Objects.nonNull(getOpenId())){ openId = getOpenId(); }
        } catch (Exception e){
            log.error("getOpenId()获取信息失败",e);
        }
        if(Objects.isNull(openId)){
            openId = (String) redisUtil.get(req.getHeader("X-Access-Token"));
        }
        log.info("openId：{}",openId);


        LambdaQueryWrapper<WxUserinfo> query = Wrappers.lambdaQuery();
        query.eq(WxUserinfo::getOpenid,openId);
        log.info(openId);
        log.info(wxUserinfoService.toString());
        WxUserinfo wxUserinfo = wxUserinfoService.getOne(query); //获取微信用户
        if(Objects.isNull(wxUserinfo)){
            return ResultMapper.<String>error().setMsg("您的信息错误，请新登录。");
        }

        LambdaQueryWrapper<Patient> patientQuery = Wrappers.lambdaQuery();
        patientQuery.eq(Patient::getWxUserinfoId,wxUserinfo.getId());
        patientQuery.orderByDesc(Patient::getCreateTime);
        List<Patient> patientList = patientService.list(patientQuery); //获者当前用户患者列表

        return ResultMapper.<List>ok().setData(patientList);
    }
    @GetMapping("/detail")
    public Result detail(@RequestParam("patientId") String patientId,
                         HttpServletRequest req) {
        Result<?> result = new Result<>();
        String url = Common.operateUrl("addpaint/"+patientId);
        //token不存在，重新授权
        if(Objects.isNull(req.getHeader("X-Access-Token"))){
            result.setCode(250);
            result.setMsg(url);
            return result;
        }
        String openId = null;
        try{
            if(Objects.nonNull(getOpenId())){ openId = getOpenId(); }
        } catch (Exception e){
            log.error("getOpenId()获取信息失败",e);
        }
        if(Objects.isNull(openId)){
            openId = (String) redisUtil.get(req.getHeader("X-Access-Token"));
        }
        log.info("openId：{}",openId);
        if(Objects.isNull(openId)){
            result.setCode(250);
            result.setMsg(url);
            return result;
        }



        LambdaQueryWrapper<WxUserinfo> query = Wrappers.lambdaQuery();
        query.eq(WxUserinfo::getOpenid,openId);
        WxUserinfo wxUserinfo = wxUserinfoService.getOne(query); //获取微信用户
        if(Objects.isNull(wxUserinfo)){
            return ResultMapper.<String>error().setMsg("您的信息错误，请新登录。");
        }
        LambdaQueryWrapper<Patient> patientQuery = Wrappers.lambdaQuery();
        patientQuery.eq(Patient::getWxUserinfoId,wxUserinfo.getId());
        patientQuery.eq(Patient::getId,patientId);
        Patient patient =patientService.getOne(patientQuery); //获者当前用户患者列表
        if(Objects.isNull(patient)){
            return ResultMapper.<String>error().setMsg("该患者不是您创建，无权查看。");
        }
        return ResultMapper.<Patient>ok().setData(patient);
    }

    /**
     * 患者信息保存
     * @param patientVo
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody PatientRequestVo patientVo,
                       HttpServletRequest req) {
        //token不存在，重新授权
        Result<?> result = new Result<>();
        String openId = null;
        try{
            if(Objects.nonNull(getOpenId())){ openId = getOpenId(); }
        } catch (Exception e){
            log.error("getOpenId()获取信息失败",e);
        }
        if(Objects.isNull(openId)){
            openId = (String) redisUtil.get(req.getHeader("X-Access-Token"));
        }

        result = captcharService.checkMobileAndCode(patientVo.getMobile(),patientVo.getCode());
        if(!result.isSuccess()) {
            return result;
        }

        Patient patient = new Patient();
        BeanUtils.copyProperties(patientVo,patient);
        LambdaQueryWrapper<WxUserinfo> query = Wrappers.lambdaQuery();
        query.eq(WxUserinfo::getOpenid,openId);
        WxUserinfo wxUserinfo = wxUserinfoService.getOne(query); //获取微信用户

        try {
            String pinyin = PinyinUtil.getPinyin(patient.getName(),"");
            String first = PinyinUtil.getFirstLetter(patient.getName(),"");
            if (first.length() > 0){
                first = first.substring(0,1);
            }
            patient.setFirstChar(first);
            patient.setPyinShort(pinyin);
        } catch (Exception e) {
            log.error("获取患者拼音失败{}",patient.getName(),e);
        }
        patient.setCreateTime(new Date());
        patient.setUpdateTime(new Date());
        patient.setWxUserinfoId(wxUserinfo.getId());
        if(Objects.nonNull(patient.getId())){
            patientService.updateById(patient);
        }else{
            patientService.save(patient);
        }

        return ResultMapper.ok();
    }
    /**
     * 患者信息保存：挂号
     * @param patientVo
     * @return
     */
    @PostMapping("/registerSave")
    public Result registerSave(@RequestBody PatientRequestVo patientVo,
                               HttpServletRequest req,String openid){
        Result<?> result = new Result<>();
//        String url = Common.operateUrl("patient_archives/index");
//        if(Objects.isNull(req.getHeader("X-Access-Token"))){
//            result.setCode(250);
//            result.setMsg(url);
//            return result;
//        }
//        String openId = (String) redisUtil.get(req.getHeader("X-Access-Token"));
//        log.info("openId：{}",openId);
//        if(Objects.isNull(openId)){
//            result.setCode(250);
//            result.setMsg(url);
//            return result;
//        }

        Patient patient = new Patient();
        BeanUtils.copyProperties(patientVo,patient);
        LambdaQueryWrapper<WxUserinfo> query = Wrappers.lambdaQuery();
        query.eq(WxUserinfo::getOpenid,openid);
        WxUserinfo wxUserinfo = wxUserinfoService.getOne(query); //获取微信用户

        try {
            String pinyin = PinyinUtil.getPinyin(patient.getName(),"");
            String first = PinyinUtil.getFirstLetter(patient.getName(),"");
            if (first.length() > 0){
                first = first.substring(0,1);
            }
            patient.setFirstChar(first);
            patient.setPyinShort(pinyin);
        } catch (Exception e) {
            log.error("获取患者拼音失败{}",patient.getName(),e);
        }
        patient.setCreateTime(new Date());
        patient.setUpdateTime(new Date());
        patient.setWxUserinfoId(wxUserinfo.getId());

        log.info("患者数据：{}",patient);

        if(Objects.isNull(patient.getId())){
            if(patientService.save(patient)){
                result.setMsg("创建成功！");
                result.setCode(200);
            }else{
                result.setMsg("创建失败！");
                result.setCode(500);
            }
        }else{
            if(patientService.updateById(patient)){
                result.setMsg("编辑成功！");
                result.setCode(200);
            }else{
                result.setMsg("编辑失败！");
                result.setCode(500);
            }
        }
        return result;
    }

    @PostMapping("/inquiry")
    public Result<InquiryResponseVo> inquiry(@RequestBody InquiryRequestVo inquiry,
                                             HttpServletRequest req){
        String openId = null;
        try{
            if(Objects.nonNull(getOpenId())){ openId = getOpenId(); }
        } catch (Exception e){
            log.error("getOpenId()获取信息失败",e);
        }
        if(Objects.isNull(openId)){
            openId = (String) redisUtil.get(req.getHeader("X-Access-Token"));
        }
        return apiInquiryService.saveInquiry(inquiry,openId);
    }

    @GetMapping("/inquiry")
    public Result inquiry(@RequestParam String id){
        InquiryInfo inquiryInfo = inquiryInfoService.getById(id);
        if(Objects.isNull(inquiryInfo)){
            return ResultMapper.error().setMsg("没有该问诊单");
        }
        wxUserinfoService.getByOpenid(inquiryInfo.getWxuserId());
        Patient patient = patientService.getById(inquiryInfo.getPatientId());
        InquiryResponseVo vo = new InquiryResponseVo();
        BeanUtils.copyProperties(inquiryInfo,vo);

        if(Objects.nonNull(patient)){
            vo.setPatientName(patient.getName());
            vo.setPatientSex(patient.getSex().intValue()==1?"男":"女");
        }else{
            vo.setPatientName("未设置患者姓名");
            vo.setPatientSex("未知");
        }

        return ResultMapper.ok().setData(vo);
    }

//    @GetMapping("/captchar")
//    public Result captchar(@RequestParam String mobile,String code){
//        return captcharService.checkMobileAndCode(mobile,code);
//    }

    @GetMapping("code")
    public Result<?> captchar(String mobile){
        Result<?> result = new Result<>();
        if(!ValidateUtils.validateMobilePhone(mobile)){
            result.setMsg("手机号错误，请确认手机号");
            result.setCode(-1);
            return result;
        }

        Integer random=(int)((Math.random()*9+1)*100000);
        String code=random.toString();
        JSONObject jsonObject  =new JSONObject();
        jsonObject.put("code",code);
        try {
            DySmsHelper.sendSms(mobile,jsonObject, DySmsEnum.LOGIN_TEMPLATE_CODE);
            result.setCode(1);
            result.setMsg("发送成功");
            Captchar captchar = new Captchar(mobile,code);
            captcharService.save(captchar);

        } catch (ClientException e) {
            e.printStackTrace();
            result.setCode(-1);
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 删除
     * @param patientId
     * @return
     */
    @GetMapping("delete")
    public Result<?> delete(@RequestParam String patientId){
        boolean res = patientService.removeById(patientId);
        Result<?> result = new Result<>();
        if(res){
            result.setMsg("删除成功！");
            result.setCode(200);
            return result;
        }else{
            result.setMsg("删除失败！");
            result.setCode(500);
            return result;
        }
    }


    /**
     * 获取微信用户基本信息
     * @param openid
     * @return
     */
    @GetMapping("getWxInfo")
    public Result<?> getWxInfo(@RequestParam String openid){
        LambdaQueryWrapper<WxUserinfo> query = Wrappers.lambdaQuery();
        query.eq(WxUserinfo::getOpenid,openid);
        log.info(openid);
        log.info(wxUserinfoService.toString());
        WxUserinfo wxUserinfo = wxUserinfoService.getOne(query); //获取微信用户
        return ResultMapper.ok().setData(wxUserinfo);
    }

}
